package com.aube.plugin.origin;

import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.ScrollView;

import com.huyn.baseframework.utils.Utils;

/**
 * Created by huyaonan on 16/10/17.
 */
public class FreeEventScrollView extends ScrollView {
    private final String TAG = "Aube/FreeEventScrollView";

    private GestureDetector mGestureDetector;

    public FreeEventScrollView(Context context) {
        this(context, null);
    }

    public FreeEventScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FreeEventScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mGestureDetector = new GestureDetector(context, new YScrollDetector());
        setFadingEdgeLength(0);
    }

    private IDispatchScrollListener mListener;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(mListener != null && mListener.onTransparentLocation(ev)) {
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean b1 = super.onInterceptTouchEvent(ev);
        boolean b2 = mGestureDetector.onTouchEvent(ev);
        Utils.Log(TAG, "[onInterceptTouchEvent] onIntercept = " + b1 + ", onTouch  " + b2);

        int action = MotionEventCompat.getActionMasked(ev);
        if (action == MotionEvent.ACTION_DOWN) {
            return b1;  // need to take care the situation that scrolling is stopped by action_down.
        } else {
            return b1 && b2;
        }
    }

    public void setDispatchScrollListener(IDispatchScrollListener listener) {
        this.mListener = listener;
    }

    public interface IDispatchScrollListener {
        public boolean onTransparentLocation(MotionEvent ev);
    }

    // Return false if we're scrolling in the x direction
    class YScrollDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            Utils.Log(TAG, "[onScroll] distanceX = " + distanceX + ", distanceY = " + distanceY);
            return Math.abs(distanceY) > Math.abs(distanceX);
        }
    }

}
